//
//  ModelData.swift
//  codelabs
//
//  Created by 雷雷 on 23/05/2025.
//

import Foundation


/**
 Observable 自动监听数据变化和保存数据，并自动展示最新的数据
 */
@Observable
class ModelData{
    var landmarks:[Landmark]=load("landmarkData.json")
    var hikes:[Hike]=load("hikeData.json")
    var profile:Profile = Profile.default
        
    var features:[Landmark]{
        landmarks.filter{
            $0.isFeatured
        }
    }
    
    var categories:[String:[Landmark]]{
        Dictionary(
            grouping:landmarks,
            by:{$0.category.rawValue}
        )
    }
}


/**
 从文件中读取 JSON 数据，并解析到 T 模型
 */
func load<T:Decodable>(_ fileName:String)->T{
    let data:Data
    
    guard let file=Bundle.main.url(forResource: fileName, withExtension: nil)
    else {
        fatalError("Couldn't find \(fileName) in main bundle.")
    }
    
    do{
        // 从文件中读取 JSON 数据
        data=try Data(contentsOf: file)
    }catch{
        fatalError("Couldn't load file \(fileName)\n\(error)")
    }
    
    do{
        let decoder=JSONDecoder()
        // 解析 JSON 数据
        return try decoder.decode(T.self, from: data)
    }catch{
        fatalError("Couldn't parse \(fileName) as \(T.self):\n\(error)")
    }
}
